package com.googlecode.openrtp.grizzly;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.glassfish.grizzly.filterchain.BaseFilter;
import org.glassfish.grizzly.filterchain.FilterChainContext;
import org.glassfish.grizzly.filterchain.NextAction;
import com.googlecode.openrtp.spi.RtpPacket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author jocke
 */
public class FileStoreFilter extends BaseFilter {

    private static final Logger LOG = Logger.getLogger(FileStoreFilter.class.getName());

    private FileOutputStream fileWriter;

    public FileStoreFilter() {

        try {

            File file = new File(new File(System.getProperty("user.dir")), "testing.mp3");

            if (file.createNewFile()) {
                LOG.log(Level.FINE, "Created file");

            } else {
                LOG.log(Level.FINE, "File already exists!");
            }

            LOG.log(Level.OFF, "will save data at {0}", file.getAbsolutePath());

            fileWriter = new FileOutputStream(file);

        } catch (IOException e) {
            LOG.log(Level.SEVERE, "Failed to initialize file filter", e);
        }
    }

    @Override
    public NextAction handleRead(FilterChainContext ctx) throws IOException {
        RtpPacket packet = ctx.getMessage();
        fileWriter.write(packet.getPayload());
        fileWriter.flush();
        return super.handleRead(ctx);
    }
}
